package org.oimwrapper.connectors.genericldap;

import java.io.*;
import java.rmi.*;
import java.util.*;
import javax.naming.*;
import javax.naming.ldap.*;

/**
 * A serializable ldap context.
 */
public class OIMLdapSerializableContext extends InitialLdapContext implements Serializable, Remote {

	/**
	 * The reference count for this object.
	 */
	protected int referenceCount;
	
	/**
	 * Default Constructor
	 * 
	 * @param Environment The jndi environment to create the ldap connection with.
	 * @param Controls Any controls to use for the ldap connection.
	 * @exception NamingException
	 */
	public OIMLdapSerializableContext(Hashtable Environment, Control[] Controls) throws NamingException { 
		super(Environment, Controls);
		
	}
	
	/**
	 * Adjusts the reference count, and closes the connection if requested and the object
	 * is no longer in use.
	 * 
	 * @param Ammount The ammount to adjust the reference count by.
	 * @param Close <code>true</code> if the object is should be closed if no longer in use,
	 *              or <code>false</false> if the object should be closed if no longer in use.
	 * @exception NamingException
	 */
	protected synchronized void count(int Ammount, boolean Close) throws NamingException {
		referenceCount += Ammount;
		if (referenceCount <= 0 && Close) {
			super.close();
		}
	}
	
	/**
	 * Finalizer to close any remaining connections when this object is destroyed.
	 * 
	 * @exception Throwable
	 */
	protected void finalize() throws Throwable {
		super.close();
	}
	
	/**
	 * Indicates that the object is in use.
	 */
	public void markAsUsed() {
		try {
			count(1, false);
		} catch (Exception e) { ; }
	}
	
	/**
	 * Indicates that the object is no longer in use.
	 */
	public void markAsUnused() {
		try {
			count(-1, false);
		} catch (Exception e) { ; }
	}
	
	/**
	 * Closes the connection only if the object is no longer in use.
	 * 
	 * @exception NamingException
	 */
	public void close() throws NamingException {
		count(0, true);
	}
}